using System.Collections.Generic;
using System.Linq;
using ReagentStore.ERM;

namespace ReagentStore.DAL
{
	public class ReagentDAL : IDALBase<Reagent>
	{
		#region Implementation of IDALBase<T>

		public IList<Reagent> GetEntities()
		{
			using (var db = new ReagentStoreContainer(new ConnectionStringBuilder().EntityConnectionString()))
				return db.Reagents.ToList();
		}

		public Reagent GetEntityById(int id)
		{
			using (var db = new ReagentStoreContainer(new ConnectionStringBuilder().EntityConnectionString()))
				return db.Reagents.SingleOrDefault(s => id.Equals(s.ReagentID));
		}

		public void Insert(Reagent reagent)
		{
			using (var db = new ReagentStoreContainer(new ConnectionStringBuilder().EntityConnectionString()))
			{
				db.Reagents.AddObject(reagent);
				db.SaveChanges();
			}
		}

		public void Update(Reagent reagent)
		{
			using (var db = new ReagentStoreContainer(new ConnectionStringBuilder().EntityConnectionString()))
			{
				Reagent exist = GetEntityById(reagent.ReagentID);
				db.Reagents.Attach(exist);

				exist.Name = reagent.Name;
				exist.Unit = reagent.Unit;
				exist.StandingCount = reagent.StandingCount;
				exist.AlertCount = reagent.AlertCount;
				exist.AlertPeriod = reagent.AlertPeriod;
				exist.CatalogID = reagent.CatalogID;

				db.SaveChanges();
			}
		}

		public void Delete(Reagent reagent)
		{
			using (var db = new ReagentStoreContainer(new ConnectionStringBuilder().EntityConnectionString()))
			{
				Reagent exist = GetEntityById(reagent.ReagentID);
				db.Reagents.Attach(exist);
				db.Reagents.DeleteObject(exist);
				db.SaveChanges();
			}
		}

		#endregion

		public IList<Reagent> GetEntitiesByCatalogId(int catalogId)
		{
			using (var db = new ReagentStoreContainer(new ConnectionStringBuilder().EntityConnectionString()))
				return db.Reagents.Where(w => catalogId.Equals(w.CatalogID)).ToList();
		}
	}
}